<template>
  <div class="flex h-screen overflow-hidden">
    <!-- 侧边栏 -->
    <div :class="['bg-gray-900 text-white w-64 flex flex-col transition-all duration-300 ease-in-out', isSidebarOpen ? 'translate-x-0' : '-translate-x-64 md:translate-x-0']">
      <!-- 侧边栏头部 -->
      <div class="flex items-center justify-between px-4 py-3 bg-gray-800">
        <div class="flex items-center">
          <img src="https://via.placeholder.com/40" alt="Logo" class="h-8 w-8 rounded-full">
          <span class="ml-2 text-xl font-semibold">商城管理系统</span>
        </div>
        <button @click="toggleSidebar" class="md:hidden text-gray-300 hover:text-white">
          <i class="bi bi-x-lg"></i>
        </button>
      </div>
      
      <!-- 侧边栏菜单 -->
      <nav class="flex-1 overflow-y-auto py-4">
        <ul class="space-y-1">
          <li>
            <router-link to="/dashboard" class="flex items-center px-4 py-2 text-gray-300 hover:bg-gray-700 hover:text-white">
              <i class="bi bi-speedometer2 mr-3"></i>
              <span>控制台</span>
            </router-link>
          </li>
          <li>
            <router-link to="/products" class="flex items-center px-4 py-2 text-gray-300 hover:bg-gray-700 hover:text-white">
              <i class="bi bi-box-seam mr-3"></i>
              <span>商品管理</span>
            </router-link>
          </li>
          <li>
            <router-link to="/categories" class="flex items-center px-4 py-2 text-gray-300 hover:bg-gray-700 hover:text-white" active-class="bg-gray-700 text-white">
              <i class="bi bi-tags mr-3"></i>
              <span>分类管理</span>
            </router-link>
          </li>
          <li>
            <router-link to="/orders" class="flex items-center px-4 py-2 text-gray-300 hover:bg-gray-700 hover:text-white">
              <i class="bi bi-cart3 mr-3"></i>
              <span>订单管理</span>
            </router-link>
          </li>
          <li>
            <router-link to="/inventory" class="flex items-center px-4 py-2 text-gray-300 hover:bg-gray-700 hover:text-white">
              <i class="bi bi-clipboard-data mr-3"></i>
              <span>库存管理</span>
            </router-link>
          </li>
          <li>
            <router-link to="/statistics" class="flex items-center px-4 py-2 text-gray-300 hover:bg-gray-700 hover:text-white">
              <i class="bi bi-graph-up mr-3"></i>
              <span>数据统计</span>
            </router-link>
          </li>
          <li>
            <router-link to="/settings" class="flex items-center px-4 py-2 text-gray-300 hover:bg-gray-700 hover:text-white">
              <i class="bi bi-gear mr-3"></i>
              <span>系统设置</span>
            </router-link>
          </li>
        </ul>
      </nav>
      
      <!-- 侧边栏底部 -->
      <div class="p-4 bg-gray-800">
        <div class="flex items-center">
          <img src="https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?ixlib=rb-1.2.1&auto=format&fit=facearea&facepad=2&w=256&h=256&q=80" alt="用户头像" class="h-8 w-8 rounded-full">
          <div class="ml-3">
            <p class="text-sm font-medium text-white">管理员</p>
            <p class="text-xs text-gray-300">admin@example.com</p>
          </div>
        </div>
        <div class="mt-3">
          <button @click="logout" class="flex items-center justify-center px-4 py-2 text-sm text-white bg-gray-700 rounded-md hover:bg-gray-600">
            <i class="bi bi-box-arrow-left mr-2"></i>
            退出登录
          </button>
        </div>
      </div>
    </div>
    
    <!-- 主内容区 -->
    <div class="flex-1 flex flex-col overflow-hidden">
      <!-- 顶部导航栏 -->
      <header class="bg-white border-b border-gray-200 shadow-sm">
        <div class="flex items-center justify-between px-4 py-3">
          <div class="flex items-center">
            <button @click="toggleSidebar" class="text-gray-500 focus:outline-none md:hidden">
              <i class="bi bi-list text-xl"></i>
            </button>
            <h1 class="ml-4 text-lg font-semibold text-gray-700">分类管理</h1>
          </div>
          <div class="flex items-center space-x-4">
            <button class="text-gray-500 hover:text-gray-600 focus:outline-none">
              <i class="bi bi-bell"></i>
            </button>
            <button class="flex items-center text-gray-500 hover:text-gray-600 focus:outline-none">
              <img src="https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?ixlib=rb-1.2.1&auto=format&fit=facearea&facepad=2&w=256&h=256&q=80" alt="用户头像" class="h-8 w-8 rounded-full">
              <span class="ml-2 text-sm font-medium">管理员</span>
              <i class="bi bi-chevron-down ml-1"></i>
            </button>
          </div>
        </div>
      </header>
      
      <!-- 分类管理内容 -->
      <main class="flex-1 overflow-y-auto">
        <!-- 分类管理卡片 -->
        <div class="bg-white m-4 rounded-lg shadow">
          <div class="p-4 border-b border-gray-200">
            <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
              <div class="flex-1">
                <div class="relative">
                  <i class="bi bi-search text-gray-400 search-icon"></i>
                  <input type="text" v-model="searchQuery" placeholder="搜索分类名称" class="search-input p-2 border border-gray-300 rounded-lg w-full">
                </div>
              </div>
              <div>
                <button @click="openAddCategoryModal" class="bg-indigo-600 text-white px-4 py-2 rounded-lg hover:bg-indigo-700 transition flex items-center">
                  <i class="bi bi-plus-lg mr-2"></i> 添加分类
                </button>
              </div>
            </div>
          </div>

          <!-- 分类列表 -->
          <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
              <thead class="bg-gray-50">
                <tr>
                  <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    分类名称
                  </th>
                  <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    商品数量
                  </th>
                  <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    排序
                  </th>
                  <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    状态
                  </th>
                  <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    操作
                  </th>
                </tr>
              </thead>
              <tbody class="bg-white divide-y divide-gray-200">
                <!-- 没有分类数据时显示提示 -->
                <tr v-if="categories.length === 0">
                  <td colspan="5" class="px-6 py-4 text-center text-sm text-gray-500">
                    <div class="py-8">
                      <i class="bi bi-inbox text-4xl block mx-auto mb-2 text-gray-400"></i>
                      <p>{{ loading ? '正在加载分类数据...' : '暂无分类数据' }}</p>
                      <button 
                        v-if="!loading && error" 
                        @click="fetchCategories()" 
                        class="mt-2 text-indigo-600 hover:text-indigo-800 underline"
                      >
                        重新加载
                      </button>
                    </div>
                  </td>
                </tr>
                
                <!-- 遍历分类，根据层级和父子关系处理显示 -->
                <tr v-for="category in displayCategories" 
                    :key="category.id"
                    :class="[
                      'hover:bg-gray-50', 
                      {'bg-gray-50': category.isChild},
                      {'border-t border-dashed border-gray-200': category.isChild}
                    ]">
                  <td class="px-6 py-4 whitespace-nowrap" :class="{'py-3': category.isChild}">
                    <div class="flex items-center" :class="{'pl-8 border-l-2 border-indigo-200': category.isChild}">
                      <div class="flex-shrink-0 h-12 w-12 flex items-center justify-center rounded-md" 
                           :class="category.isChild ? 'bg-gray-100 text-gray-500 h-10 w-10' : 'bg-indigo-100 text-indigo-500'">
                        <i class="bi" :class="[category.icon, category.isChild ? 'text-lg' : 'text-xl']"></i>
                      </div>
                      <div class="ml-4">
                        <div class="text-sm font-medium" :class="category.isChild ? 'text-gray-700' : 'text-gray-900'">
                          {{ category.name }}
                          <span 
                            v-if="!category.isChild && getChildrenCount(category.id) > 0" 
                            class="ml-1 text-xs text-blue-500 font-semibold"
                          >
                            ({{ getChildrenCount(category.id) }}个子分类)
                          </span>
                        </div>
                        <div :class="category.isChild ? 'text-xs text-gray-500' : 'text-sm text-gray-500'">
                          {{ category.description }}
                        </div>
                      </div>
                    </div>
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500" :class="{'py-3': category.isChild}">
                    {{ category.productCount }}
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500" :class="{'py-3': category.isChild}">
                    {{ category.sort }}
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap" :class="{'py-3': category.isChild}">
                    <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full" 
                          :class="category.active ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'">
                      {{ category.active ? '启用' : '禁用' }}
                    </span>
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap text-sm font-medium" :class="{'py-3': category.isChild}">
                    <div class="flex space-x-3">
                      <button @click="editCategory(category)" class="text-indigo-600 hover:text-indigo-900">
                        编辑
                      </button>
                      <button @click="deleteCategory(category)" class="text-red-600 hover:text-red-900">
                        删除
                      </button>
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>

          <!-- 分页 -->
          <div class="bg-white px-4 py-3 flex items-center justify-between border-t border-gray-200 sm:px-6">
            <div class="flex-1 flex justify-between sm:hidden">
              <button 
                disabled
                class="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-gray-100 cursor-not-allowed"
              >
                上一页
              </button>
              <button 
                disabled
                class="ml-3 relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-gray-100 cursor-not-allowed"
              >
                下一页
              </button>
            </div>
            <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
              <div>
                <p class="text-sm text-gray-700">
                  显示 
                  <span class="font-medium">1</span> 
                  到 
                  <span class="font-medium">
                    {{ filteredCategories.length }}
                  </span> 
                  条，共 
                  <span class="font-medium">{{ filteredCategories.length }}</span> 条记录
                </p>
              </div>
            </div>
          </div>
        </div>
      </main>

      <!-- 底部 -->
      <footer class="bg-white border-t border-gray-200 px-4 py-3">
        <div class="text-center text-sm text-gray-500">
          © {{ new Date().getFullYear() }} 微信商城后台管理系统 版权所有
        </div>
      </footer>
    </div>

    <!-- 模态对话框组件 -->
    <Transition name="modal">
      <div v-if="modal.show" class="modal-backdrop" @click.self="closeModal">
        <div class="modal-content">
          <div class="p-4 border-b">
            <div class="flex justify-between items-center">
              <h3 class="text-lg font-medium" :class="getModalHeaderClass">{{ modal.title }}</h3>
              <button @click="closeModal" class="text-gray-400 hover:text-gray-500">
                <i class="bi bi-x-lg"></i>
              </button>
            </div>
          </div>
          <div class="p-4">
            <p>{{ modal.message }}</p>
            <div v-if="modal.showForm" class="mt-4 space-y-4">
              <div>
                <label for="categoryName" class="block text-sm font-medium text-gray-700 mb-1">
                  分类名称 <span class="text-red-500">*</span>
                </label>
                <input 
                  type="text" 
                  id="categoryName" 
                  v-model="modal.formData.name" 
                  class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
                  placeholder="请输入分类名称（必填）"
                />
              </div>
              <div>
                <label for="categoryDescription" class="block text-sm font-medium text-gray-700 mb-1">
                  分类描述
                </label>
                <textarea 
                  id="categoryDescription" 
                  v-model="modal.formData.description" 
                  rows="3"
                  class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
                  placeholder="请输入分类描述（选填）"
                ></textarea>
              </div>
              <div>
                <label for="categorySort" class="block text-sm font-medium text-gray-700 mb-1">
                  排序值
                </label>
                <input 
                  type="number" 
                  id="categorySort" 
                  v-model="modal.formData.sort" 
                  class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
                  placeholder="请输入排序值"
                  min="0"
                />
              </div>
              <div>
                <label for="categoryIcon" class="block text-sm font-medium text-gray-700 mb-1">
                  图标
                </label>
                <div class="grid grid-cols-4 gap-2 mb-2">
                  <button 
                    v-for="icon in availableIcons" 
                    :key="icon"
                    @click="selectIcon(icon)"
                    class="flex items-center justify-center p-3 border rounded-md hover:bg-indigo-50"
                    :class="modal.formData.icon === icon ? 'border-indigo-500 bg-indigo-50' : 'border-gray-300'"
                  >
                    <i class="bi text-xl" :class="icon"></i>
                  </button>
                </div>
              </div>
              <div class="flex items-center">
                <input 
                  type="checkbox" 
                  id="categoryStatus" 
                  v-model="modal.formData.status" 
                  class="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded"
                />
                <label for="categoryStatus" class="ml-2 block text-sm text-gray-700">
                  启用分类
                </label>
              </div>
              <div>
                <label for="parentCategory" class="block text-sm font-medium text-gray-700 mb-1">
                  父级分类
                </label>
                <select 
                  id="parentCategory" 
                  v-model="modal.formData.parentId" 
                  class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
                  :disabled="modal.formData.isTopLevel"
                  :class="{'bg-gray-100': modal.formData.isTopLevel}"
                >
                  <option :value="null">无父级(顶级分类)</option>
                  <option 
                    v-for="cat in categories.filter(c => !c.parentId && c.id !== modal.formData.id)" 
                    :key="cat.id" 
                    :value="cat.id"
                  >
                    {{ cat.name }}
                  </option>
                </select>
                <p v-if="modal.formData.isTopLevel" class="mt-1 text-sm text-gray-500">
                  顶级分类不能选择父级分类
                </p>
              </div>
            </div>
          </div>
          <div class="px-4 py-3 bg-gray-50 flex justify-end space-x-2 rounded-b-lg">
            <button v-if="modal.showCancelButton" @click="closeModal" class="px-4 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 bg-white hover:bg-gray-50">
              {{ modal.cancelButtonText }}
            </button>
            <button @click="confirmModal" :class="getModalConfirmButtonClass" class="px-4 py-2 border border-transparent rounded-md text-sm font-medium text-white">
              {{ modal.confirmButtonText }}
            </button>
          </div>
        </div>
      </div>
    </Transition>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user.js'
import { getCategories, getCategoriesTree, createCategory, updateCategory, deleteCategory as deleteCategoryApi } from '@/api/index.js'

// 用户存储和路由
const userStore = useUserStore()
const router = useRouter()

// 侧边栏状态
const isSidebarOpen = ref(false)

// 切换侧边栏
function toggleSidebar() {
  isSidebarOpen.value = !isSidebarOpen.value
}

// 退出登录
function logout() {
  userStore.logout()
  router.push({ name: 'login' })
}

// 搜索条件
const searchQuery = ref('')

// 分类数据
const categories = ref([])
const loading = ref(false)
const error = ref(null)

// 可选图标列表
const availableIcons = [
  'bi-tag',
  'bi-phone',
  'bi-laptop',
  'bi-tv',
  'bi-handbag',
  'bi-basket',
  'bi-camera',
  'bi-droplet',
  'bi-egg-fried',
  'bi-cart',
  'bi-house',
  'bi-gift',
  'bi-briefcase',
  'bi-shop',
  'bi-book',
  'bi-headphones'
]

// 选择图标
const selectIcon = (icon) => {
  modal.value.formData.icon = icon
}

// 模态对话框状态
const modal = ref({
  show: false,
  title: '',
  message: '',
  type: 'info', // info, success, warning, danger
  confirmButtonText: '确定',
  cancelButtonText: '取消',
  showCancelButton: true,
  showForm: false,
  formData: {
    id: null,
    name: '',
    description: '',
    icon: 'bi-tag',
    sort: 0,
    status: true
  },
  callback: null
})

// 模态对话框样式计算属性
const getModalHeaderClass = computed(() => {
  switch (modal.value.type) {
    case 'success': return 'text-green-600';
    case 'warning': return 'text-yellow-600';
    case 'danger': return 'text-red-600';
    default: return 'text-gray-900';
  }
})

const getModalConfirmButtonClass = computed(() => {
  switch (modal.value.type) {
    case 'success': return 'bg-green-600 hover:bg-green-700';
    case 'warning': return 'bg-yellow-600 hover:bg-yellow-700';
    case 'danger': return 'bg-red-600 hover:bg-red-700';
    default: return 'bg-indigo-600 hover:bg-indigo-700';
  }
})

// 根据搜索条件过滤分类
const filteredCategories = computed(() => {
  if (!searchQuery.value) {
    return categories.value
  }
  
  return categories.value.filter(category => 
    category.name.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
    category.description.toLowerCase().includes(searchQuery.value.toLowerCase())
  )
})

// 将分类组织成父子结构的展示列表
const displayCategories = computed(() => {
  const result = []
  
  // 先获取所有顶级分类
  const topLevelCategories = filteredCategories.value.filter(c => !c.parentId)
  
  // 对每个顶级分类，添加自身，然后添加其子分类
  topLevelCategories.forEach(parent => {
    // 添加父分类
    result.push({
      ...parent,
      isChild: false
    })
    
    // 获取并添加子分类
    const children = getChildCategories(parent.id)
    children.forEach(child => {
      result.push({
        ...child,
        isChild: true
      })
    })
  })
  
  return result
})

// 分组后的分类数据，用于树形结构展示
const groupedCategories = computed(() => {
  // 获取所有顶级分类
  return filteredCategories.value.filter(c => !c.parentId)
})

// 获取分类的子分类
function getChildCategories(parentId) {
  if (!parentId) return []
  return filteredCategories.value.filter(c => c.parentId === parentId)
}

// 获取分类的子分类数量
function getChildrenCount(parentId) {
  return getChildCategories(parentId).length
}

// 获取分类数据
async function fetchCategories() {
  try {
    loading.value = true
    error.value = null
    
    // 使用新的树形结构API
    const response = await getCategoriesTree()
    
    if (response && response.categories) {
      // 在开发模式下记录原始数据结构，便于调试
      if (import.meta.env.DEV) {
        console.log('原始分类树形数据:', response.categories)
      }
      
      // 将树形结构扁平化处理，包含所有层级的分类
      categories.value = flattenCategoryTree(response.categories)
      
      // 对分类进行排序，确保UI显示顺序一致
      categories.value.sort((a, b) => {
        // 首先按层级排序
        if (a.level !== b.level) {
          return a.level - b.level
        }
        // 然后按排序值排序
        return a.sort - b.sort
      })
    } else {
      // 如果API获取失败，使用一些默认数据
      categories.value = getDefaultCategories()
    }
  } catch (err) {
    console.error('获取分类列表出错:', err)
    error.value = '获取分类数据失败，请稍后再试'
    // 加载失败时使用默认数据
    categories.value = getDefaultCategories()
  } finally {
    loading.value = false
  }
}

// 辅助函数：扁平化处理分类树形结构
function flattenCategoryTree(treeData, level = 1, parentName = '') {
  let result = []
  
  if (!Array.isArray(treeData)) {
    return result
  }
  
  for (const category of treeData) {
    // 构建当前分类对象
    const formattedCategory = {
      id: category._id,
      _id: category._id,
      name: category.name || '未命名分类',
      description: category.description || category.desc || '',
      fullName: parentName ? `${parentName} > ${category.name}` : category.name,
      icon: (category.icon && category.icon.startsWith('bi-')) ? category.icon : getIconForCategory(category.name || ''),
      productCount: category.productCount || category.count || 0,
      sort: category.sort || 0,
      active: category.isActive !== undefined ? category.isActive : (category.active !== undefined ? category.active : true),
      parentId: category.parentId || null,
      level: level,
      hasChildren: Array.isArray(category.children) && category.children.length > 0
    }
    
    // 添加当前分类到结果
    result.push(formattedCategory)
    
    // 递归处理子分类
    if (Array.isArray(category.children) && category.children.length > 0) {
      const childCategories = flattenCategoryTree(
        category.children, 
        level + 1,
        formattedCategory.name
      )
      result = result.concat(childCategories)
    }
  }
  
  return result
}

// 根据分类名称获取合适的图标
function getIconForCategory(name) {
  // 如果已经是有效的Bootstrap图标类名格式，直接返回
  if (name && name.startsWith('bi-')) {
    return name;
  }
  
  // 根据分类名称包含的关键词返回适合的图标
  const iconMap = {
    '手机': 'bi-phone',
    '数码': 'bi-camera',
    '电脑': 'bi-laptop',
    '办公': 'bi-briefcase',
    '电器': 'bi-tv',
    '家用': 'bi-house',
    '服装': 'bi-handbag',
    '鞋': 'bi-boot',
    '美妆': 'bi-droplet',
    '个护': 'bi-shield',
    '食品': 'bi-egg-fried',
    '生鲜': 'bi-basket'
  }
  
  for (const [keyword, icon] of Object.entries(iconMap)) {
    if (name && name.includes(keyword)) {
      return icon
    }
  }
  
  // 默认图标
  return 'bi-tag'
}

// 获取默认分类数据（API获取失败时使用）
function getDefaultCategories() {
  return [
    {
      id: 1,
      name: '手机数码',
      description: '包含手机、平板电脑等数码产品',
      icon: 'bi-phone',
      productCount: 156,
      sort: 1,
      active: true,
      parentId: null
    },
    {
      id: 2,
      name: '电脑办公',
      description: '包含笔记本电脑、台式机、办公设备等',
      icon: 'bi-laptop',
      productCount: 89,
      sort: 2,
      active: true,
      parentId: null
    },
    {
      id: 3,
      name: '家用电器',
      description: '包含电视、冰箱、洗衣机等大型家电',
      icon: 'bi-tv',
      productCount: 64,
      sort: 3,
      active: true,
      parentId: null
    },
    {
      id: 4,
      name: '服装鞋包',
      description: '包含男女服装、鞋靴、箱包等',
      icon: 'bi-handbag',
      productCount: 215,
      sort: 4,
      active: true,
      parentId: null
    },
    {
      id: 5,
      name: '美妆个护',
      description: '包含化妆品、个人护理用品等',
      icon: 'bi-droplet',
      productCount: 78,
      sort: 5,
      active: true,
      parentId: null
    },
    {
      id: 6,
      name: '食品生鲜',
      description: '包含零食、饮料、生鲜食品等',
      icon: 'bi-egg-fried',
      productCount: 96,
      sort: 6,
      active: false,
      parentId: null
    }
  ]
}

// 打开模态对话框
function showModal(options) {
  modal.value = {
    show: true,
    title: options.title || '提示',
    message: options.message || '',
    type: options.type || 'info',
    confirmButtonText: options.confirmButtonText || '确定',
    cancelButtonText: options.cancelButtonText || '取消',
    showCancelButton: options.showCancelButton !== undefined ? options.showCancelButton : true,
    showForm: options.showForm !== undefined ? options.showForm : false,
    formData: options.formData || {
      id: null,
      name: '',
      description: '',
      icon: 'bi-tag',
      sort: 0,
      status: true
    },
    callback: options.callback || null
  }
}

// 关闭模态对话框
function closeModal() {
  modal.value.show = false
}

// 确认模态对话框
function confirmModal() {
  if (modal.value.callback) {
    modal.value.callback(modal.value.formData)
  }
  closeModal()
}

// 打开添加分类模态框
function openAddCategoryModal() {
  showModal({
    title: '添加分类',
    message: '请填写分类信息',
    type: 'info',
    showForm: true,
    formData: {
      id: null,
      name: '',
      description: '',
      icon: 'bi-tag',
      sort: categories.value.length + 1,
      status: true,
      parentId: null
    },
    confirmButtonText: '保存',
    callback: async (formData) => {
      try {
        // 验证
        if (!formData.name.trim()) {
          throw new Error('分类名称不能为空')
        }
        
        // 准备API数据
        const categoryData = {
          name: formData.name.trim(),
          description: formData.description.trim(),
          icon: formData.icon,
          sort: formData.sort,
          isActive: formData.status,
          parentId: formData.parentId // 发送父分类ID
        }
        
        // 调用API创建分类
        const result = await createCategory(categoryData)
        
        if (result && result.success) {
          // 调试日志
          if (import.meta.env.DEV) {
            console.log('创建分类成功，返回数据:', result.category)
          }
          
          // 添加成功后重新获取分类树
          await fetchCategories()
          
          // 显示成功提示
          showModal({
            title: '添加成功',
            message: `分类 "${formData.name}" 已成功添加`,
            type: 'success',
            showCancelButton: false
          })
        } else {
          throw new Error(result?.message || '添加分类失败')
        }
      } catch (err) {
        console.error('创建分类出错:', err)
        
        // 显示错误提示
        showModal({
          title: '添加失败',
          message: err.message || '添加分类失败，请稍后再试',
          type: 'danger',
          showCancelButton: false
        })
      }
    }
  })
}

// 编辑分类
function editCategory(category) {
  // 判断是否为顶级分类（没有parentId或parentId为null）
  const isTopLevelCategory = !category.parentId;
  
  showModal({
    title: '编辑分类',
    message: '请修改分类信息',
    type: 'info',
    showForm: true,
    formData: {
      id: category.id,
      name: category.name,
      description: category.description,
      icon: category.icon,
      sort: category.sort,
      status: category.active,
      parentId: category.parentId,
      isTopLevel: isTopLevelCategory // 标记是否为顶级分类
    },
    confirmButtonText: '保存',
    callback: async (formData) => {
      try {
        // 验证
        if (!formData.name.trim()) {
          throw new Error('分类名称不能为空')
        }
        
        // 准备API数据 - 根据API文档只发送必要的字段
        const categoryData = {
          name: formData.name.trim(),
          icon: formData.icon,
          sort: formData.sort,
        }
        
        // 仅当编辑子分类时才发送parentId字段，编辑顶级分类时不需要
        if (formData.parentId && !formData.isTopLevel) {
          categoryData.parentId = formData.parentId
        }
        
        // 添加可选的isActive字段
        if (formData.status !== undefined) {
          categoryData.isActive = formData.status;
        }
        
        // 开发环境记录即将发送的请求数据
        if (import.meta.env.DEV) {
          console.log('发送更新分类请求，ID:', formData.id, '数据:', categoryData);
        }
        
        // 调用API更新分类
        const result = await updateCategory(formData.id, categoryData)
        
        if (result && result.success) {
          // 更新成功后重新获取分类树
          await fetchCategories()
          
          // 显示成功提示
          showModal({
            title: '编辑成功',
            message: `分类 "${formData.name}" 已成功更新`,
            type: 'success',
            showCancelButton: false
          })
        } else {
          throw new Error(result?.message || '更新分类失败')
        }
      } catch (err) {
        console.error('更新分类出错:', err)
        
        // 显示错误提示
        showModal({
          title: '编辑失败',
          message: err.message || '编辑分类失败，请稍后再试',
          type: 'danger',
          showCancelButton: false
        })
      }
    }
  })
}

// 删除分类
function deleteCategory(category) {
  // 检查是否有子分类
  const hasChildren = categories.value.some(c => c.parentId === category.id)
  
  if (hasChildren) {
    showModal({
      title: '无法删除',
      message: `分类 "${category.name}" 下有子分类，请先删除子分类。`,
      type: 'warning',
      showCancelButton: false
    })
    return
  }
  
  showModal({
    title: '删除分类',
    message: `确定要删除分类 "${category.name}" 吗？该操作不可撤销。`,
    type: 'danger',
    confirmButtonText: '删除',
    callback: async () => {
      try {
        // 调用API删除分类
        const result = await deleteCategoryApi(category.id)
        
        if (result && result.success) {
          // 删除成功后重新获取分类树
          await fetchCategories()
          
          // 显示成功提示
          showModal({
            title: '删除成功',
            message: `分类 "${category.name}" 已成功删除`,
            type: 'success',
            showCancelButton: false
          })
        } else {
          throw new Error(result?.message || '删除分类失败')
        }
      } catch (err) {
        console.error('删除分类出错:', err)
        
        // 显示错误提示
        showModal({
          title: '删除失败',
          message: err.message || '删除分类失败，请稍后再试',
          type: 'danger',
          showCancelButton: false
        })
      }
    }
  })
}

// 页面加载时获取分类数据
onMounted(() => {
  fetchCategories()
})
</script>

<style scoped>
/* 搜索框图标样式 */
.search-icon {
  position: absolute;
  left: 12px;
  top: 50%;
  transform: translateY(-50%);
  pointer-events: none;
  z-index: 1;
}

/* 搜索框内边距调整 */
.search-input {
  padding-left: 36px !important;
}

/* 模态对话框样式 */
.modal-backdrop {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 50;
}

.modal-enter-active,
.modal-leave-active {
  transition: opacity 0.3s ease;
}

.modal-enter-from,
.modal-leave-to {
  opacity: 0;
}

.modal-content {
  background-color: white;
  border-radius: 0.5rem;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
  transform: scale(1);
  transition: transform 0.3s ease;
}

.modal-enter-from .modal-content,
.modal-leave-to .modal-content {
  transform: scale(0.9);
}
</style> 